package com.yj.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yj.entity.Classes;
import com.yj.entity.Student;
import com.yj.mapper.ClassesMapper;
import com.yj.mapper.StudentMapper;
import com.yj.service.StudentService;
import com.yj.util.PageResult;
import com.yj.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Collections;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private ClassesMapper classesMapper;
	/**
	 * 1. 查询所有学生列表
	 * @return
	 */
	@Override
	public List<Student> findAll() {
		List<Student> students = studentMapper.selectAll();
		for (Student student : students) {
			Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
			student.setCname(classes.getCname());
		}
		return students;
	}

	/**
	 * 2. 分页查询学生信息
	 * @param page      当前页
	 * @param pageSize  每页大小
	 * @return
	 */
	@Override
	public PageResult<Student> findByPage(Integer page, Integer pageSize) {
		// 1. 开始分页
		PageHelper.startPage(page, pageSize);
		// 2. 查询所有学生列表
		List<Student> students = findAll();
		// 3. 转换为Page对象
		Page<Student> iPage = (Page<Student>) students;
		// 4. 构造PageResult对象
		return new PageResult<>(iPage.getTotal(), iPage.getResult());
	}

	/**
	 * 3. 条件查询带分页
	 * @param page
	 * @param pageSize
	 * @param vo
	 * @return
	 */
	@Override
	public PageResult<Student> search(Integer page, Integer pageSize, StudentVO vo) {
		// 3.1 开始分页
		PageHelper.startPage(page, pageSize);
		// 3.2 设置查询条件
		Example example = new Example(Student.class);
		Example.Criteria criteria = example.createCriteria();
		if(vo != null){
			if(StrUtil.isNotBlank(vo.getSname())) {
				criteria.andLike("sname", "%" + vo.getSname() + "%");
			}
			if(StrUtil.isNotBlank(vo.getAddr())){
				criteria.andLike("addr","%" + vo.getAddr() + "%");
			}
			if(vo.getCid() != null && vo.getCid() != 0){
				criteria.andEqualTo("cid",vo.getCid());
			}
		}
		// 3.3 开始查询
		List<Student> students = studentMapper.selectByExample(example);
		// 3.4 将上面的对象转换为Page对象
		Page<Student> studentPage = (Page<Student>) students;
		// 3.5 处理学生所在的班级名称（默认是班级编号，看的效果不明显）
		List<Student> result = studentPage.getResult();
		for (Student student : result) {
			Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
			student.setCname(classes.getCname());
		}
		// 3.6 最后，返回我们的PageResult对象
		return new PageResult<>(studentPage.getTotal(),result );
	}

}
